/**
 * @留言板
 */
import { getPageInformation, getCommentContent, getSuggestedReading , myRelease } from '@/services';
import { PageDataType, CommentDataType, RecommendDataType } from '@/utils/type';
import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';

// 定义模块内部状态的类型
export interface MsgboardModelState {
  // 页面信息
  PageInformation: PageDataType;
  // 评论区数据
  CommentContent: CommentDataType[];
  // 推荐阅读数据
  SuggestedReading: RecommendDataType[]; 
}

// 定义模块的类型
export interface MsgboardModelType {
  namespace: 'msgboard';
  state: MsgboardModelState;
  effects: {
    getPageInformation: Effect;
    getCommentContent: Effect;
    getSuggestedReading: Effect;
    myRelease:Effect;
  };
  reducers: {
    save: Reducer<MsgboardModelState>;
  };
}

const MsgboardModel: MsgboardModelType = {
  // 模块命名空间
  namespace: 'msgboard',

  // 模块内部状态
  state: {
    PageInformation: {} as PageDataType,
    CommentContent: [],
    SuggestedReading: [],
  },

  // 副作用
  effects: {
    //获取页面信息
    *getPageInformation({ payload }, { call, put }) {
      const result = yield call(getPageInformation);
      if (result.statusCode === 200) {
        yield put({
          type: 'save',
          payload: {
            PageInformation: result.data
          }
        })
      }
    },
    // 获取评论区数据
    *getCommentContent({ payload }, { call, put }) {
      const result = yield call(getCommentContent);
      if (result.statusCode === 200) {
        yield put({
          type: "save",
          payload: {
            CommentContent: result.data[0]
          }
        })
      }
    },
    // 获取推荐阅读数据
    *getSuggestedReading({ payload }, { call, put }) {
      const result = yield call(getSuggestedReading);
      if (result.statusCode === 200) {
        yield put({
          type: "save",
          payload: {
            SuggestedReading: result.data
          }
        })
      }
    },
    //发布评论
    *myRelease({ payload }, { call, put }) {
      const result = yield call(myRelease,payload.id,payload.content,payload.url);
      if (result.statusCode === 200) {
        yield put({
          type: "save",
        })
      }
    }
  },

  // 同步修改
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    }
  }
};

export default MsgboardModel;

